'use strict';
const { Model } = require('sequelize');
const moment = require('moment/moment');
moment.locale('zh-cn');
const { Conflict } = require('http-errors');
const { coursesIndex } = require('../utils/meilisearch');
module.exports = (sequelize, DataTypes) => {
  class Course extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
      models.Course.belongsTo(models.Category, { as: 'category' });
      models.Course.belongsTo(models.User, { as: 'user' });
      models.Course.hasMany(models.Chapter, { as: 'chapters' });
      models.Course.belongsToMany(models.User, {
        through: models.Like,
        foreignKey: 'courseId',
        as: 'likeUsers',
      });
    }
  }
  Course.init(
    {
      categoryId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          notNull: { msg: '分类ID必须填写' },
          notEmpty: { msg: '分类ID不能为空' },
          async isPresent(value) {
            const category = await sequelize.models.Category.findByPk(value);
            if (!category) {
              throw new Conflict(`ID为: ${value} 的分类不存在`);
            }
          },
        },
      },
      userId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          notNull: { msg: '用户ID必须填写' },
          notEmpty: { msg: '用户ID不能为空' },
          async isPresent(value) {
            const category = await sequelize.models.User.findByPk(value);
            if (!category) {
              throw new Conflict(`ID为: ${value} 的用户不存在`);
            }
          },
        },
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: { msg: '课程名必须填写' },
          notEmpty: { msg: '课程名不能为空' },
          async isPresent(value) {
            const category = await Course.findOne({ where: { name: value } });
            if (category) {
              throw new Conflict(`课程为: ${value} 的名称已存在`);
            }
          },
        },
      },
      image: DataTypes.STRING,
      recommended: DataTypes.BOOLEAN,
      introductory: DataTypes.BOOLEAN,
      content: DataTypes.TEXT,
      likesCount: DataTypes.INTEGER,
      chaptersCount: DataTypes.INTEGER,
      free: {
        type: DataTypes.BOOLEAN,
        validate: {
          isIn: { args: [[true, false]], msg: '是否免费课程的值必须是，推荐true 不推荐false' },
        },
      },
      createdAt: {
        type: DataTypes.DATE,
        get() {
          return moment(this.getDataValue('createdAt')).format('LL');
        },
      },
      updatedAt: {
        type: DataTypes.DATE,
        get() {
          return moment(this.getDataValue('updatedAt')).format('LL');
        },
      },
    },
    {
      sequelize,
      modelName: 'Course',
      hooks: {
        // 创建课程后执行的操作 
        afterCreate: async(course) => {

        },
        // 更新课程执行的操作
        afterUpdate: async (course) => {
          // await coursesIndex.updateDocuments
        },
        afterDestroy: async(course) => {
          // 删除课程执行的操作
        }
      }
    }
  );
  return Course;
};
